(function(window, undefined) {
	let that;

	function Map(option) {
		option = option || {};
		this.snack = option.snack;
		this.food = option.food;
		this.map = option.map;
		this.time;
		
		that = this;

		this.render();
		this.start();
	}
	Map.prototype = {
		constructor: Map,
		render: function() {
			this.snack.render();
			this.food.render();
		},
		start: function() {
			this.time = setInterval(function() {
				that.snack.move();
				that.isGameOver();
			}, 200);
		},
		isGameOver: function() {
			let headX = this.snack.body[0].x;
			let headY = this.snack.body[0].y;
			if (headX < 0 || headX > this.map.offsetWidth / this.snack.width - 1) {
				clearInterval(this.time);
				alert('游戏失败');
			}
			if (headY < 0 || headY > this.map.offsetHeight / this.snack.height - 1) {
				clearInterval(this.time);
				alert('游戏失败');
			}
		}
	}

	// 开启点击事件
	function control() {
		document.addEventListener('keydown', function(e) {
			e = e || window.event;
			let keyCode = e.keyCode;	// 87 83 65 68
			switch(keyCode) {
				case 87: 
					that.snack.decration = 'up';
					break;
				case 83: 
					that.snack.decration = 'down';
					break;
				case 65: 
					that.snack.decration = 'left';
					break;
				case 68: 
					that.snack.decration = 'right';
					break;
				default: 
					break;
			}
		}, false);
	}
	control();

	window.Map = Map;
})(window, undefined);
